import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'
import { toast } from '../utils/toast'
import store from '../store'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: Home
  },
  {
    path: '/allgoods',
    name: 'AllGoods',
    component: () => import(/* webpackChunkName: "allgoods" */ '../views/AllGoods.vue')
  },
  {
    path: '/personal',
    name: 'Personal',
    component: () => import(/* webpackChunkName: "personal" */ '../views/Personal.vue'),
    // 如果进入一个父路由，想要自动跳转到其中一个子路由
    redirect:'/personal/cart', // 跳转的子路由要写全
    children: [
      {
        // path:'/personal/cart',  // 完整写法
        path: 'cart', // 简单写法
        name: 'Cart',
        component: () => import(/* webpackChunkName: "cart" */ '../components/personal/Cart.vue'),
      },
      {
        path: 'user', // 简单写法
        name: 'User',
        component: () => import(/* webpackChunkName: "user" */ '../components/personal/User.vue'),
      }
    ]
  },
  {
    path: '/myorders',
    name: 'MyOrders',
    component: () => import(/* webpackChunkName: "myorders" */ '../views/MyOrders.vue')
  },
  // {
  //   path: '/frees',
  //   name: 'Frees',
  //   component: () => import(/* webpackChunkName: "frees" */ '../views/Frees.vue')
  // },
  {
    path: '/gooddetail',
    name: 'GoodDetail',
    component: () => import(/* webpackChunkName: "gooddetail" */ '../views/GoodDetail.vue')
  },
  {
    path:'*', // 匹配任何路径 -- 一般可以用来做 404 页面
    component:()=> import('../views/NotFound.vue')
  }
]

const router = new VueRouter({
  // 路由的历史模式还是哈希模式，取决于这个地方使用的 mode
  // vue-router 默认其实是 哈希模式，我们之前在使用vue-cli 创建的时候，选择了 历史模式，所以生成的 index.js mode 是 history
  // mode: 'history',
  base: process.env.BASE_URL,
  routes
})

// 全局前置守卫
router.beforeEach((to, from, next) => {
  // 判断是否已经登录，如果已经登录，才让访问 personal , myorders
  // 如果访问的是 person 或者 myorders
  const regPersonal = /\/personal/
  const regMyOrders = /\/myorders/
  if (regPersonal.test(to.path) || regMyOrders.test(to.path)) {
    // 条件： 1. token 是否存在  
    const token = localStorage.getItem('x-auth-token')
    if (!token) {
      return toast('请先登录', 'warnning')
    }
    // 2. token 是否过期
    // 两种做法： 2.1  vuex 里面有没有userInfo的内容
    //            2.2 在每次登录成功后，都存一个 过期时间在 localstroage里面
    // if(!store.state.userInfo.username){
    //   return  toast('登录状态失效，请重新登录', 'warnning')
    // }
  }
  next()
})

export default router
